import { create } from "zustand";

interface DashboardState {
  dashBoardInfo: Record<string, any>;
  loading: boolean;
  init: () => Promise<void>;
  saveInfo: (info: Record<string, any>) => Promise<void>;
}

export const useDashboardStore = create<DashboardState>((set) => ({
  dashBoardInfo: {},
  loading: false,

  // 从 storage 初始化仪表盘信息
  init: async () => {
    try {
      set({ loading: true });
      const result = await chrome.storage.local.get('dashboardInfo');
      if (result.dashboardInfo) {
        set({ dashBoardInfo: result.dashboardInfo });
      }
    } catch (error) {
      console.error('Failed to init dashboard info:', error);
    } finally {
      set({ loading: false });
    }
  },

  // 保存仪表盘信息到 storage
  saveInfo: async (info: Record<string, any>) => {
    try {
      set({ loading: true });
      await chrome.storage.local.set({ dashboardInfo: info });
      set({ dashBoardInfo: info }); // ✅ 正确更新 dashBoardInfo 字段
    } catch (error) {
      console.error("Failed to save dashboard info:", error);
      throw error;
    } finally {
      set({ loading: false });
    }
  },
}));
